class Solution {
public:
    int n, m;
    vector<vector<int>> grid;
    bool check[51][51];
    int ret;
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    
    int maxAreaOfIsland(vector<vector<int>>& g) {
        n = g.size();
        m = g[0].size();
        grid = g;
        ret = 0;
      
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 1 && !check[i][j]) {
                    check[i][j] = true;
                    int area = dfs(i, j);
                    ret = max(ret, area);
                }
            }
        }
        return ret;
    }
    
    int dfs(int i, int j) {
        int area = 1; // 当前单元格
        for (int k = 0; k < 4; k++) {
            int x = dx[k] + i;
            int y = dy[k] + j;
            if (x >= 0 && x < n && y >= 0 && y < m && !check[x][y] && grid[x][y] == 1) {
                check[x][y] = true;
                area += dfs(x, y); // 累加所有相邻单元格的面积
            }
        }
        return area;
    }
};